import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:hzy_normal_widget/hzy_getx_utils.dart';
import 'package:hzy_normal_widget/hzy_normal_utils.dart';
import 'package:ttcomment/ttcomment.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:webview_flutter/webview_flutter.dart';

import 'common_index.dart';

class CommonWebPage extends TTNormalStatefulWidget {
  const CommonWebPage({Key? key}) : super(key: key);

  @override
  TTNormalState<TTNormalStatefulWidget> getState() {
    return _CommonWebPageState();
  }
}

class _CommonWebPageState extends CommonStateWidget<CommonWebPage> {
  /// 属性
  ///
  ///

  String webtitle = "";
  @override
  String? get title => webtitle;
  WebViewController? webViewController;
  PageState webstate = PageState.initializedState;
  @override
  PageState get pageState => webstate;
  @override
  bool get safeAreabottm => false;

  int failnum = 1;
  bool isfail = false;

  /// 网页url
  String url = "";

  /// 生命周期
  ///
  ///

  /// 界面初始化
  @override
  void initDefaultState() {
    super.initDefaultState();
    url = currentGetArguments();
  }

  /// 界面销毁
  @override
  void initDefaultDispose() {
    super.initDefaultDispose();
  }

  /// 网路请求
  ///
  ///

  /// 构建视图
  ///
  ///

  @override
  Widget createBody(BuildContext context) {
    return WebView(
      initialUrl: url,
      javascriptMode: JavascriptMode.unrestricted,
      onWebViewCreated: (WebViewController controller) {
        configsetState(() {
          webViewController = controller;
        });
      },
      navigationDelegate: (NavigationRequest request) {
        return NavigationDecision.navigate;
      },
      onPageStarted: (String url) {},
      onPageFinished: (String url) {
        webViewController?.getTitle().then((value) {
          configsetState(() {
            webtitle = value ?? "";
          });
        });
      },
      onWebResourceError: (error) {
        debugprint(error.errorCode);
        configsetState(() {
          failnum = 0;
          webstate = PageState.errorState;
        });
      },
    );
  }

  /// 触发方法
  ///
  ///

  /// 配置默认数据
  @override
  void configNormalData() {}

  void reload() {
    failnum++;
    webViewController?.reload();
  }

  @override
  void tapplachold(CommonPlaceHoldType type) {
    configsetState(() {
      webstate = PageState.initializedState;
    });
    reload();
  }
}
